package com.oracle.lingshangejia.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.iflytek.cloud.ErrorCode;
import com.iflytek.cloud.InitListener;
import com.iflytek.cloud.RecognizerResult;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechUtility;
import com.iflytek.cloud.ui.RecognizerDialog;
import com.iflytek.cloud.ui.RecognizerDialogListener;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.oracle.lingshangejia.Constant;
import com.oracle.lingshangejia.R;
import com.oracle.lingshangejia.adapter.FieledMissionDetailsAdapter;
import com.oracle.lingshangejia.base.BaseActivity;
import com.oracle.lingshangejia.bean.FieledMissionDetailsBean;
import com.oracle.lingshangejia.bean.FieledUpInfoBean;
import com.oracle.lingshangejia.bean.ImgBean;
import com.oracle.lingshangejia.utils.JsonParser;
import com.oracle.lingshangejia.utils.OkHttpUtils;
import com.oracle.lingshangejia.utils.UIUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
//寻医问药详情
public class FieledMissionsDetailsActivity extends BaseActivity implements OnClickListener {
    private TextView tv_title;
    private ImageButton ib_back;
    private RecyclerView hd_recycleview;
    private FieledMissionDetailsAdapter adapter;
    private TextView tv_fieledsendperson;
    private TextView tv_fieled_date;
    private TextView tv_fieled_title;
    private ImageView iv_addimg;
    private RelativeLayout rl_fieledreport_ok;
    private ImageView iv_speech;
    private EditText et_fieled_content;
    private List<LocalMedia> selectList = new ArrayList<>();
    private int xyid;
    private int xywyid;
    private Timer timer;
    // 用HashMap存储听写结果
    private HashMap<String, String> mIatResults = new LinkedHashMap<String, String>();
    @Override
    public int intiLayout() {
        return R.layout.activity_fieledmissionsdetails;
    }

    @Override
    public void initView() {
        tv_title=findViewById(R.id.tv_title);
        tv_title.setText("问题详情");
        ib_back=findViewById(R.id.ib_back);
        ib_back.setOnClickListener(this);
        hd_recycleview=findViewById(R.id.hd_recycleview);
        tv_fieledsendperson=findViewById(R.id.tv_fieledsendperson);
        et_fieled_content=findViewById(R.id.et_fieled_content);
        tv_fieled_date=findViewById(R.id.tv_fieled_date);
        tv_fieled_title=findViewById(R.id.tv_fieled_title);
        iv_addimg=findViewById(R.id.iv_addimg);
        rl_fieledreport_ok=findViewById(R.id.rl_fieledreport_ok);
        iv_speech=findViewById(R.id.iv_speech);
        iv_speech.setOnClickListener(this);
        rl_fieledreport_ok.setOnClickListener(this);
        iv_addimg.setOnClickListener(this);
        hd_recycleview.setNestedScrollingEnabled(false);
        SpeechUtility.createUtility(this, SpeechConstant.APPID + "=5cc53c41");
        UIUtils.adaptSoftInput(getWindow().getDecorView(), et_fieled_content);
    }

    @Override
    public void initData() {
        LinearLayoutManager linearLayoutManager=new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        hd_recycleview.setLayoutManager(linearLayoutManager);
        if(getIntent()!=null){
            xywyid=getIntent().getIntExtra("xywyId",0);
            timer=new Timer();
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    getNetFieledMissionsDetails(xywyid);
                }
            },0,10000);//每隔一秒使用handler发送一下消息,也就是每隔一秒执行一次,一直重复执行
        }
    }
    private void getNetFieledMissionsDetails(int xywyId) {
        HashMap<Object,Object> map = new HashMap<>();
        map.put("xywyId",xywyId);
        OkHttpUtils.getNetWork(this, Constant.baseurl+"online/xywy/xywyDetail",map,handler);
    }

    @SuppressLint("HandlerLeak")
    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 1:
                    try{
                        String s= (String) msg.obj;
                        Gson gson=new Gson();
                        FieledMissionDetailsBean bean=gson.fromJson(s,FieledMissionDetailsBean.class);
                        if(bean.getCode()==0){
                            adapter=new FieledMissionDetailsAdapter(FieledMissionsDetailsActivity.this,bean.getData().getWyjl(),bean.getData().getUsfUrl(),bean.getData().getGsfUrl());
                            hd_recycleview.setAdapter(adapter);
                            String sex="";
                            int jmxb = bean.getData().getJmxb();
                            if(jmxb==1){
                                sex="女";
                            }else{
                                sex="男";
                            }
                            tv_fieledsendperson.setText("发布人："+bean.getData().getJmxm()+" "+sex);
                            tv_fieled_date.setText(bean.getData().getCreateDate());
                            tv_fieled_title.setText(bean.getData().getWtbt());
                            xyid=bean.getData().getXywyId();

                        }else{
                            Toast.makeText(FieledMissionsDetailsActivity.this,bean.getMsg(),Toast.LENGTH_SHORT).show();
                        }

                    }catch (Exception e){
                        e.printStackTrace();
                    }
                    break;
                case 2: //连接上服务器，错误
                    String error= (String) msg.obj;
                    Toast.makeText(FieledMissionsDetailsActivity.this,error,Toast.LENGTH_SHORT).show();
                    break;
                case 3:  //没有网络
                    Toast.makeText(FieledMissionsDetailsActivity.this,"网络不可用",Toast.LENGTH_SHORT).show();
                    break;
                case 4: //没有连接上服务器
                    Toast.makeText(FieledMissionsDetailsActivity.this,"连接服务器失败",Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.ib_back:
                finish();
                break;
            case R.id.iv_addimg:
                // 进入相册 以下是例子：用不到的api可以不写
                PictureSelector.create(FieledMissionsDetailsActivity.this)
                        .openGallery(PictureMimeType.ofImage())//全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                        .theme(R.style.picture_default_style)//主题样式(不设置为默认样式) 也可参考demo values/styles下 例如：R.style.picture.white.style
                        .maxSelectNum(1)// 最大图片选择数量 int
                        .minSelectNum(1)// 最小选择数量 int
                        .withAspectRatio(1,1)
                        .imageSpanCount(4)// 每行显示个数 int
                        .previewImage(true)// 是否可预览图片 true or false
                        .isCamera(true)// 是否显示拍照按钮 true or false
                        .imageFormat(PictureMimeType.PNG)// 拍照保存图片格式后缀,默认jpeg
                        .setOutputCameraPath("/CustomPath")// 自定义拍照保存路径,可不填
                        .enableCrop(true)// 是否裁剪 true or false
                        .compress(true)// 是否压缩 true or false
                        .compressSavePath(getPath())//压缩图片保存地址
                        .circleDimmedLayer(true)// 是否圆形裁剪 true or false
                        .previewEggs(false)// 预览图片时 是否增强左右滑动图片体验(图片滑动一半即可看到上一张是否选中) true or false
                        .minimumCompressSize(100)// 小于100kb的图片不压缩
                        .synOrAsy(true)//同步true或异步false 压缩 默认同步
                        .isDragFrame(false)// 是否可拖动裁剪框(固定)
                        .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code
                break;
            case R.id.rl_fieledreport_ok:
                String content=et_fieled_content.getText().toString();
                if (TextUtils.isEmpty(content)&&selectList.size()==0) {
                    Toast.makeText(FieledMissionsDetailsActivity.this,"请输入您想说的内容或者图片",Toast.LENGTH_SHORT).show();
                    return;
                }
                if(selectList.size()!=0){
                    getNetUpImg();
                }else{
                    getNetUpInfo(-1);
                }
                break;
            case R.id.iv_speech:
                //⑧申请录制音频的动态权限
                if(ContextCompat.checkSelfPermission(this, android.Manifest.permission.RECORD_AUDIO)
                        != PackageManager.PERMISSION_GRANTED){
                    ActivityCompat.requestPermissions(this,new String[]{
                            android.Manifest.permission.RECORD_AUDIO},1);
                }else {
                    // 显示听写对话框
                    startSpeechDialog();
                }
                break;
        }
    }
    /**
     * ⑨重写onRequestPermissionsResult方法
     * 获取动态权限请求的结果
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if(requestCode==1&&grantResults[0]==PackageManager.PERMISSION_GRANTED){

        }else {
            Toast.makeText(this,"用户拒绝了权限",Toast.LENGTH_SHORT).show();
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }
    private void startSpeechDialog() {
        //1. 创建RecognizerDialog对象
        RecognizerDialog mDialog = new RecognizerDialog(this, new MyInitListener());
        //2. 设置accent、 language等参数
        mDialog.setParameter(SpeechConstant.LANGUAGE, "zh_cn");// 设置中文
        mDialog.setParameter(SpeechConstant.ACCENT, "mandarin");
        // 若要将UI控件用于语义理解，必须添加以下参数设置，设置之后 onResult回调返回将是语义理解
        // 结果
        // mDialog.setParameter("asr_sch", "1");
        // mDialog.setParameter("nlp_version", "2.0");
        //3.设置回调接口
        mDialog.setListener(new MyRecognizerDialogListener());
        //4. 显示dialog，接收语音输入
        mDialog.show();
    }
    class MyRecognizerDialogListener implements RecognizerDialogListener {

        /**
         * @param results
         * @param isLast  是否说完了
         */
        @Override
        public void onResult(RecognizerResult results, boolean isLast) {
            String result = results.getResultString(); //为解析的
            System.out.println(" 没有解析的 :" + result);
            String text = JsonParser.parseIatResult(result);//解析过后的
            System.out.println(" 解析后的 :" + text);
            String sn = null;
            // 读取json结果中的 sn字段
            try {
                JSONObject resultJson = new JSONObject(results.getResultString());
                sn = resultJson.optString("sn");
            } catch (JSONException e) {
                e.printStackTrace();
            }
            mIatResults.put(sn, text);//没有得到一句，添加到
            StringBuffer resultBuffer = new StringBuffer();
            for (String key : mIatResults.keySet()) {
                resultBuffer.append(mIatResults.get(key));
            }
            et_fieled_content.setText(resultBuffer.toString());
        }

        @Override
        public void onError(SpeechError speechError) {

        }
    }

    class MyInitListener implements InitListener {

        @Override
        public void onInit(int code) {
            if (code != ErrorCode.SUCCESS) {
                // showTip("初始化失败 ");
            }

        }
    }
    /**
     * 上传图片
     */
    private void getNetUpImg() {
        List<File> list=new ArrayList<>();
        File file=new File(selectList.get(0).getCutPath());
        list.add(file);
        OkGo.<String>post(Constant.baseurl+"open/uploadImg")
                .tag(this)
                .isMultipart(true)
                .addFileParams("files",list)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        Log.e("上传", response.body());
                        Gson gson=new Gson();
                        ImgBean bean=gson.fromJson(response.body(),ImgBean.class);
                        if(bean.getCode()==0){
                            getNetUpInfo(bean.getFileUrl().get(0));
                        }else{
                            Toast.makeText(FieledMissionsDetailsActivity.this,bean.getMsg(),Toast.LENGTH_SHORT).show();
                        }
                    }
                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        Toast.makeText(FieledMissionsDetailsActivity.this,"网络错误",Toast.LENGTH_SHORT).show();
                    }
                });
    }

    /**
     * 上传信息
     * @param id
     */
    private void getNetUpInfo(int id) {
        String content=et_fieled_content.getText().toString().trim();
        HashMap<Object, Object> map = new HashMap<>();
        map.put("yxwyId",xyid);
        if(id!=-1){
            map.put("picid1",id);
        }
        map.put("wdnr",content);
        map.put("wdType",2);
        OkHttpUtils.getNetWork(FieledMissionsDetailsActivity.this, Constant.baseurl+"online/xywy/xywywd",map,schandler);
    }
    private Handler schandler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                    case 1:  //成功S
                        String s= (String) msg.obj;
                        Gson gson=new Gson();
                        FieledUpInfoBean bean=gson.fromJson(s,FieledUpInfoBean.class);
                        if(bean.getCode()==0){
                            getNetFieledMissionsDetails(xywyid);
                            et_fieled_content.setText("");
                            iv_addimg.setImageDrawable(getResources().getDrawable(R.drawable.ic_task_add));

                        }else{
                            Toast.makeText(FieledMissionsDetailsActivity.this,bean.getMsg(),Toast.LENGTH_SHORT).show();
                        }
                        break;
                    case 2: //连接上服务器，错误
                        String error= (String) msg.obj;
                        Toast.makeText(FieledMissionsDetailsActivity.this,error,Toast.LENGTH_SHORT).show();
                        break;
                    case 3:  //没有网络
                        Toast.makeText(FieledMissionsDetailsActivity.this,"网络不可用",Toast.LENGTH_SHORT).show();
                        break;
                    case 4: //没有连接上服务器
                        Toast.makeText(FieledMissionsDetailsActivity.this,"连接服务器失败",Toast.LENGTH_SHORT).show();
                        break;
                }
        }
    };
    /**
     * 自定义压缩存储地址
     *
     * @return
     */
    private String getPath() {
        String path = Environment.getExternalStorageDirectory() + "/Luban/image/";
        File file = new File(path);
        if (file.mkdirs()) {
            return path;
        }
        return path;
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PictureConfig.CHOOSE_REQUEST && resultCode == RESULT_OK){
            // 图片选择结果回调
            selectList = PictureSelector.obtainMultipleResult(data);
            // 例如 LocalMedia 里面返回三种path
            // 1.media.getPath(); 为原图path
            // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true
            // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true
            // 如果裁剪并压缩了，已取压缩路径为准，因为是先裁剪后压缩的

            for (LocalMedia media : selectList) {
                Log.i("图片-----》", media.getPath());
                File file=new File(media.getCutPath());
                //设置图片
                Glide.with(FieledMissionsDetailsActivity.this)
                        .load(file.getPath())
                        .into(iv_addimg);
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(timer!=null){
            timer.cancel();
        }
    }
}
